package com.i2silly.wxbot.quartz.job;

import com.i2silly.wxbot.config.TempCache;
import com.i2silly.wxbot.constant.WxRobotConstant;
import com.i2silly.wxbot.pojo.WsReceive;
import com.i2silly.wxbot.utils.PubUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * @program: wx-bot
 * @description：移出聊天唤醒wxid
 * @author: pzhongqiang@linewell.com
 * @date: 2020年12月16日 10:13:29
 */
@Component
@DisallowConcurrentExecution
public class RemoveChatJob implements Job {

    Logger logger = LoggerFactory.getLogger(RemoveChatJob.class);

    @Autowired
    private TempCache cache;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        Map<String, WsReceive> map = cache.getAllLastWsReceive();
        if (PubUtils.isEmpty(map)){
            return;
        }
        logger.info("执行聊天列表删除，总共：" + map.size());
        Set<String> set = map.keySet();
        if (PubUtils.isEmpty(set)) {
            return;
        }
        for (String s : set) {
            WsReceive wsReceive = map.get(s);
            if (wsReceive == null) {
                map.remove(s);
                continue;
            }
            long timestamp = PubUtils.toSecondsTimestamp(wsReceive.getTime());
            long curTime = System.currentTimeMillis() / 1000;
            if (curTime - timestamp >= 60) {
                map.remove(s);
            }
        }
        logger.info("聊天列表删除完毕，现存" + map.size());
        cache.addCache(WxRobotConstant.LAST_RECEIVE_MSG, map);
    }
}
